'use strict';

const Controller = require('egg').Controller;
const api = require('../../config/api');

class NewsController extends Controller {
  async index() {
    const { ctx } = this;
    // 处理请求参数：
    const page = ctx.request.query.page;
    const id = ctx.request.query.id;
    if (id) {
      // 新闻详情
      const res = await ctx.curl(`${api.basicUrl}/News/getNewsItem`, {
        method: 'GET',
        contentType: 'json',
        dataType: 'json',
        data: {
          newsid: id,
        },
      });
      ctx.logger.info(`page: ${page}, res: ${res.data.rows}`);
      await ctx.render('news.html', {
        pageData: res.data,
        isDetail: true,
        routerName: '/news',
        current: Number(page) || 1,
      });
    } else {
      // 获取新闻
      const res = await ctx.curl(`${api.basicUrl}/News/getNewsList`, {
        method: 'GET',
        contentType: 'json',
        dataType: 'json',
        data: {
          page: page || 1,
          pagesize: 7,
        },
      });
      ctx.logger.info(`page: ${page}, res: ${res.data.rows}`);
      console.log('res:', res.data);
      // 筛选出置顶新闻
      const data = res.data.rows || [];
      let i = 0;
      let topInfo = null;
      for (; i < data.length; i++) {
        if (data[i].topflag === '1') {
          topInfo = data[i];
          break;
        }
      }
      await ctx.render('news.html', {
        pageData: res.data,
        topInfo,
        isDetail: false,
        routerName: '/news',
        current: Number(page) || 1,
      });
    }
  }
}

module.exports = NewsController;
